import mongoose from 'mongoose'
import bodyparser from 'koa-bodyparser'
import user from './user'
import add from './goods'

const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const redisStore = require("koa-redis")
const session = require("koa-generic-session")

const app = new Koa()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

async function start () {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  mongoose.connect('mongodb://127.0.0.1:27017/lla', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
  })

  app.keys = ['lla']

  app.use(session({
    cookie: {
      path: "/",
      httpOnly: true,
      maxAge: 7 * 60 * 60 * 1000
    },
    store: redisStore({
      all: "127.0.0.1:6379"
    })
  }))

  app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }))

  app.use(user.routes()).use(user.allowedMethods())
  app.use(add.routes()).use(add.allowedMethods())
  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
